package com.corpgovernment.travelstandard.controller;

import com.corpgovernment.api.travelstandard.enums.AreaTypeEnum;
import com.corpgovernment.api.travelstandard.utils.MyMap;
import com.corpgovernment.api.travelstandard.vo.*;
import com.corpgovernment.api.travelstandard.vo.request.AppPersonSearchCityRequest;
import com.corpgovernment.api.travelstandard.vo.response.AppPersonSearchCityResponse;
import com.corpgovernment.common.base.BaseUserInfo;
import com.corpgovernment.common.base.JSONResult;
import com.corpgovernment.common.utils.BaseUtils;
import com.corpgovernment.travelstandard.impl.AreaConfigService;
import com.corpgovernment.travelstandard.impl.CityConfigService;
import com.corpgovernment.travelstandard.impl.MbTravelstandHotelPriceService;
import com.corpgovernment.travelstandard.impl.MbTravelstandHotelQuarterService;
import com.corpgovernment.travelstandard.vo.HotelCityRequestVo;
import com.corpgovernment.travelstandard.vo.HotelDelCityRequestVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/hotelCity")
public class HotelCityController {

    @Autowired
    private AreaConfigService areaConfigService;
    @Autowired
    private CityConfigService cityConfigService;
    @Autowired
    private MbTravelstandHotelPriceService travelstandHotelPriceService;
    @Autowired
    private MbTravelstandHotelQuarterService travelstandHotelQuarterService;

    /**
     * 获取地区配置列表
     * @param
     * @return
     */
    @RequestMapping("get")
    public JSONResult getAreaDefaultCity(@RequestBody @Validated(HotelCityRequestVo.Day.class) HotelCityRequestVo requestVo) {
        Map areaDefaultCity = areaConfigService.getAreaDefaultCity(requestVo.getOrgid());
        return JSONResult.success(areaDefaultCity);
    }

    /**
     * 删除地区配置
     * @param requestVo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping("del")
    public JSONResult delAreaById(@RequestBody @Validated(HotelCityRequestVo.Week.class) HotelCityRequestVo requestVo) {

        //该区域已被酒店差标使用，不可删除
        int checkNumber = travelstandHotelPriceService.checkPriceUpperLimit(Long.valueOf(requestVo.getId()));
        if(checkNumber > 0){
            return JSONResult.errorMsg("该区域已被酒店差标使用，不可删除!");
        }

//        List<MbTravelstandHotelPriceVo> travelstandHotelPriceVos = travelstandHotelPriceService.list(new MbTravelstandHotelPriceVo(){{setTsHotelAreaId(Long.valueOf(requestVo.getId()));}});
//        if (travelstandHotelPriceVos.size() > 0) {
//            return JSONResult.errorMsg("该区域已被酒店差标使用，不可删除!");
//        }

        //删除所有差标下该地区的价格
        travelstandHotelPriceService.deleteByAreaId(Long.valueOf(requestVo.getId()));
        //删除所有差标下该地区的淡旺季信息
        travelstandHotelQuarterService.deleteByAreaId(Long.valueOf(requestVo.getId()));
        //查找该组织下的其它地区id
        List<AreaVo> areaConfigVos = areaConfigService.getAreaConfigList(new AreaConfigVo(){{
            setOrgId(String.valueOf(requestVo.getOrgid()));
            setStatus(NumberUtils.INTEGER_ZERO);
            setAreaType(AreaTypeEnum.TYPE_1.getCode());
            setHotelType(requestVo.getHotelType());
        }});
        if (areaConfigVos== null || areaConfigVos.size() != 1){
            return JSONResult.errorMsg("删除失败");
        }
        AreaVo otherArea = areaConfigVos.get(0);
        //将该地区下的城市移入其它城市
        cityConfigService.updateAreaIdByAreaId(otherArea.getId(),Long.parseLong(requestVo.getId()));
        //逻辑删除
        AreaConfigVo areaConfigVo = new AreaConfigVo();
        areaConfigVo.setOrgId(requestVo.getOrgid());
        areaConfigVo.setId(Long.parseLong(requestVo.getId()));
        areaConfigService.updateStatus(areaConfigVo);
        //判断当前组织下的地区是否为空，如果是空，则将【其它地区】类型的地区改名为“国内城市”
        int num = areaConfigService.getAreaConfigList(new AreaConfigVo(){{
            setOrgId(String.valueOf(requestVo.getOrgid()));
            setStatus(NumberUtils.INTEGER_ZERO);
            setAreaType(AreaTypeEnum.TYPE_0.getCode());
            setHotelType(requestVo.getHotelType());
        }}).size();
        if (num == 0){
            areaConfigService.update(new AreaConfigVo(){{
                setId(otherArea.getId());
                if(AreaTypeEnum.HOTEL_TYPE_0.getCode().equals(requestVo.getHotelType())){
                    setAreaName("国内城市");
                }else if(AreaTypeEnum.HOTEL_TYPE_1.getCode().equals(requestVo.getHotelType())){
                    setAreaName("海外城市");
                }

            }});
        }
        return JSONResult.success(new HashMap<>());
    }

    /**
     * 编辑地区配置
     * @param requestVo
     * @return
     */
    @RequestMapping("edit")
    public JSONResult saveOrUpdateArea(@RequestBody @Validated(HotelCityRequestVo.Month.class) HotelCityRequestVo requestVo) {
        AreaConfigVo areaConfigVo = areaConfigService.saveOrUpdate(requestVo.getId(),requestVo.getOrgid(), requestVo.getName(), requestVo.getHotelType());
        Map jsonObject = new HashMap();
        if (areaConfigVo != null) {
            jsonObject.put("id",areaConfigVo.getId());
            jsonObject.put("name",areaConfigVo.getAreaName());
        }
        return JSONResult.success(jsonObject);
    }

    /**
     * 获取城市信息
     * @param requestVo
     * @return
     */
    @RequestMapping("getCityInfo")
    public JSONResult getCityInfo(@RequestBody @Validated(HotelCityRequestVo.Year.class) HotelCityRequestVo requestVo) {
        AreaConfigVo areaConfigVo = new AreaConfigVo();
        areaConfigVo.setOrgId(requestVo.getOrgid());
        areaConfigVo.setId(Long.parseLong(requestVo.getId()));
        areaConfigVo.setHotelType(requestVo.getHotelType());
        MyMap<String, CityVo> cityMap = cityConfigService.getCityInfoList(areaConfigVo);
        Map jsonObject = new HashMap();
        if (BaseUtils.isNotNull(cityMap)) {
            jsonObject.put("cityList", cityMap.getData());
        }
        return JSONResult.success(jsonObject);
    }


    /**
     * 获取城市信息
     * @return
     */
    @RequestMapping("getCityInfoByCityId")
    public JSONResult getCityInfoByCityId(BaseUserInfo baseUserInfo,@RequestBody HotelCityRequestVo requestVo) {
        requestVo.setOrgid(baseUserInfo.getCorpId());
        return getCityInfo(requestVo);
    }


    /**
     * 删除地区城市
     * @param requestVo
     * @return
     */
    @RequestMapping("delCity")
    public JSONResult delCityByAreaIdAndCityId(@RequestBody @Validated HotelDelCityRequestVo requestVo) {
        //查找该组织下的其它地区id
        List<AreaVo> areaConfigVos = areaConfigService.getAreaConfigList(new AreaConfigVo(){{
            setOrgId(String.valueOf(requestVo.getOrgid()));
            setStatus(NumberUtils.INTEGER_ZERO);
            setAreaType(AreaTypeEnum.TYPE_1.getCode());
            setHotelType(requestVo.getHotelType());
        }});
        if (areaConfigVos== null || areaConfigVos.size() != 1){
            return JSONResult.errorMsg("删除失败");
        }
        //将该城市移入其它城市
        cityConfigService.updateAreaIdById(Long.parseLong(requestVo.getId()),areaConfigVos.get(0).getId());
        return JSONResult.success(new HashMap<>());
    }

    /**
     * 添加地区城市
     * @param addCityVo
     * @return
     */
    @RequestMapping("addCity")
    public JSONResult addCity(@RequestBody @Validated AddCityVo addCityVo) {
        if (addCityVo == null) {
            return JSONResult.errorMsg("添加城市列表参数为空！");
        }
        Map jsonObject= new HashMap();
        if(AreaTypeEnum.HOTEL_TYPE_0.getCode().equals(addCityVo.getHotelType())){
            jsonObject = cityConfigService.addCity(addCityVo);
        }else{
            jsonObject = cityConfigService.addCountry(addCityVo);
        }

        return JSONResult.success(jsonObject);
    }

    /**
     * APP个人页面查询城市
     * @return
     */
    @Deprecated
    @RequestMapping("appPersonSearchCity")
    public JSONResult appPersonSearchCity(@RequestBody AppPersonSearchCityRequest appPersonSearchCityRequest, BaseUserInfo baseUserInfo){
        List<AppPersonSearchCityResponse> appPersonSearchCityRespons = new ArrayList<>();
        String cityName = appPersonSearchCityRequest.getCityName();
        String corpId = baseUserInfo.getCorpId();
        List<CityConfigVo> cityConfigVos;
        //名称模糊查询
        cityConfigVos = cityConfigService.list(new CityConfigVo(){{
            setOrgId(corpId);
            setCityName(cityName);
        }});
        if (cityConfigVos.size() == 0){
            //缩写模糊查询
            cityConfigVos = cityConfigService.list(new CityConfigVo(){{
                setOrgId(corpId);
                setCityAbbreviation(cityName.toUpperCase());
            }});
        }
        if (cityConfigVos.size() == 0){
            //拼音模糊查询
            cityConfigVos = cityConfigService.list(new CityConfigVo(){{
                setOrgId(corpId);
                setCityPinyin(cityName.toLowerCase());
            }});
        }
        for (CityConfigVo cityConfigVo : cityConfigVos){
            AppPersonSearchCityResponse appPersonSearchCityResponse = new AppPersonSearchCityResponse();
            appPersonSearchCityResponse.setCityCode(cityConfigVo.getCityCode());
            appPersonSearchCityResponse.setCityName(cityConfigVo.getCityName());
            appPersonSearchCityResponse.setId(String.valueOf(cityConfigVo.getId()));
            appPersonSearchCityRespons.add(appPersonSearchCityResponse);
        }
        return JSONResult.success(appPersonSearchCityRespons);
    }


}
